package main

import (
	"errors"
	"time"
)

type Timer struct {
	duration time.Duration
	quit chan bool
}

func NewTimer(d time.Duration) *Timer {
	return &Timer{
		duration: d,
		quit: make(chan bool, 0),
	}
}

func (this *Timer) Start(task func()) {
	ticker := time.NewTicker(this.duration)

	go func() {
		for {
			select {
			case <- ticker.C:
				task()
			case <- this.quit:
				ticker.Stop()
				return
			}
		}
	}()
}

func (this *Timer) Stop() {
	this.quit <- true
}

func (this *Timer) Dispose() error {
	var err error
	func() {
		defer func() {
			if r := recover(); r != nil {
				switch x := r.(type) {
				case string:
					err = errors.New(x)
				case error:
					err = x
				default:
					err = errors.New("unknown panic")
				}
			}
		}()
		close(this.quit)
	}()

	return err
}
